package com.aspire.ability.auth.test;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;

//这两个包没有提示的话，直接复制这两个， rt.jar的包有这两个
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSaDemoCode {

	static String publicKey_1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2FMmfMMs3iV1tpCW5LWy7WnershYTbWyKKVtjVhRk0NXgg509XUtKQaVVxNRunI5hryK6j9fV5c5kjrGJupfI3/8HIvQGCO/zpCJPX9uVDi+uQnrqKhgLFnKRKlHWIhMBrI2C/qaE7p1T5FOgRLnWDi7RIKP/+GgPbpeG1AAi3QIDAQAB";

	// 公钥解密
	public static String decryptByPublicKey(String param, String publicKey)
			throws Exception {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bates = decoder.decodeBuffer(param);
		byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.DECRYPT_MODE, publicK);
		int inputLen = bates.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > 128) {
				cache = cipher.doFinal(bates, offSet, 128);
			} else {
				cache = cipher.doFinal(bates, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * 128;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		String pubDecode = new String(decryptedData, "UTF-8");
		return pubDecode;
	}

	// 公钥加密
	public static String encryptByPublicKey(String param, String publicKey)
			throws Exception {

		byte[] data = param.getBytes("UTF-8");
		if (data == null || publicKey == null) {
			throw new NullPointerException("encryptByPublicKey data||publicKey is null");
		}

		byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		// 对数据加密
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;

		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > 117) {
				cache = cipher.doFinal(data, offSet, 117);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}

			out.write(cache, 0, cache.length);
			i++;
			offSet = i * 117;
		}

		byte[] encryptedData = out.toByteArray();
		out.close();
		return new BASE64Encoder().encode(encryptedData);
	}
}
